<script setup lang="ts">
defineOptions({
  name: "WaterPolo"
});
import { liquidfillCircleData } from "@/components/ReChart/samples";
import "echarts-liquidfill";
import { onMounted, onUnmounted, reactive, ref, nextTick, markRaw } from "vue";

// 创建一个深拷贝，避免引用原始数据
const data = reactive(JSON.parse(JSON.stringify(liquidfillCircleData)));
const setIntervalID = ref(null);
let num = ref(0.6);
let chartInstance = ref(null);

// 修改水球图配置，使其更明显
data.series[0].label.formatter = function () {
  return Math.round(num.value * 100) + "%";
};
// data.series[0].label.fontSize = 30;
// data.series[0].label.color = "#ffffff";

// 修改水球图的颜色
// data.series[0].color = ["#044493", "#0a5ac2", "#1e80ff"];

/**每个五秒更新一次数据 */
const setIntervalfun = () => {
  setIntervalID.value = setInterval(() => {
    // 设置上限，避免数值过大
    if (num.value >= 0.95) {
      num.value = 0.2;
    }

    // 更新所有波浪数据
    data.series[0].data = [
      num.value,
      num.value - 0.05,
      num.value - 0.1,
      num.value - 0.15
    ];

    // 更新标签
    data.series[0].label.formatter = function () {
      return Math.round(num.value * 100) + "%";
    };

    // 如果图表实例存在，调用setOption更新
    if (chartInstance.value) {
      chartInstance.value.setOption({
        series: [
          {
            data: [
              num.value,
              num.value - 0.05,
              num.value - 0.1,
              num.value - 0.15
            ]
          }
        ]
      });
    }

    // 打印当前值，便于调试
    console.log("当前水球值:", num.value);

    num.value += 0.01;
  }, 5000);
};

// 获取图表实例的回调函数
const onChartInit = chart => {
  chartInstance.value = markRaw(chart);
};

onMounted(() => {
  // 确保初始数据正确设置
  data.series[0].data = [
    num.value,
    num.value - 0.05,
    num.value - 0.1,
    num.value - 0.15
  ];

  // 启动定时器
  nextTick(() => {
    setIntervalfun();
  });
});

onUnmounted(() => {
  if (setIntervalID.value) {
    clearInterval(setIntervalID.value);
  }
});
</script>

<template>
  <div class="water-polo">
    <div class="waterPolo-title">
      <dv-decoration-7
        :color="['#3183b8', '#3183b8']"
        style="width: 150px; height: 30px"
      >
        品牌曝光提升
      </dv-decoration-7>
    </div>
    <ReChart
      :data="data"
      style="width: 80%; height: 80%"
      @chart-init="onChartInit"
    />
  </div>
</template>

<style lang="scss" scoped>
.water-polo {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding-top: 13px;
  color: #fff;

  .waterPolo-title {
    box-sizing: border-box;
    font-size: 14 x;
    font-weight: bold;
    text-align: center;
  }
}
</style>
